//
//  StoreListViewController.m
//  WisdomZhuHai
//
//  Created by Admin on 14-10-27.
//  Copyright (c) 2014年 wyd. All rights reserved.
//

#import "StoreListViewController.h"
#import "ProtocolManager.h"
#import "HotRateView.h"
#import "StoreDetailViewController.h"

@interface StoreListViewController ()

@property (nonatomic,strong) UIView* headerView;
@property (nonatomic,strong) UIView* headerPopupView;

@property (nonatomic,assign) int currentIndex;
@property (nonatomic,strong) NSMutableArray* storeList;
@property (nonatomic,strong) NSArray* areaList;

@end

static const CGFloat HEADER_BUTTON_HEIGHT = 34.f;

@implementation StoreListViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.currentIndex = -1;
    
    self.areaList = @[@"香洲区", @"拱北区", @"斗门区", @"金湾区", @"高新区", @"横琴新区"];
    [self setupHeaderView];

    self.tableView.backgroundColor = [UIColor whiteColor];
//    [self setEnableRefresh:YES];
    [self setEnableLoadMore:YES];
    self.pullTableViewDelegate = self;
    self.tableView.frame = CGRectMake(0, self.headerView.bounds.size.height, self.view.bounds.size.width, self.view.bounds.size.height - self.headerView.bounds.size.height);
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 4.f)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.f)];
    
    [self getStoreList];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)onClickArea:(id)sender
{
    NSLog(@"onClickArea");
    if (self.headerPopupView.hidden) {
        [self showHeaderPopupView];
    }
    else {
        [self hideHeaderPopupView];
    }
}

- (void)onClickNearby:(id)sender
{
    NSLog(@"onClickNearby");
}

- (void)onClickAreaCategory:(UIButton*)sender
{
    NSLog(@"onClickAreaCategory %@", sender.titleLabel.text);
    if ([self.area isEqualToString:sender.titleLabel.text]) {
        return;
    }
    self.area = sender.titleLabel.text;
    [self getStoreList];
}

- (void)onTapHeaderPopupView:(UIGestureRecognizer*)gesture
{
    NSLog(@"onTapHeaderPopupView");
    [self hideHeaderPopupView];
}

#pragma mark - Protocol request
- (void)getStoreList
{
    [[ProtocolManager shareInstance] getStoresList:self.type returnCount:STORE_LIST_RETURN_COUNT beginNo:self.currentIndex+1 area:self.area star:nil storeType:nil target:self selector:@selector(getStoreListCallback:)];
}

#pragma mark - Protocol call back

- (void)getStoreListCallback:(NSDictionary*)dic
{
    NSLog(@"getStoreListCallback %@", dic);
    if (dic == nil) {
        [self resetPullTableViewState];
        return;
    }
    if (self.currentIndex == -1) {
        self.storeList = [NSMutableArray array];
    }
    NSArray* storeList = [Common valueForKey:P_LIST dic:dic];
    if ([storeList isKindOfClass:[NSArray class]]) {
        [self.storeList addObjectsFromArray:storeList];
        self.currentIndex += storeList.count;
    }
    if (storeList.count < STORE_LIST_RETURN_COUNT) {
        [self setEnableLoadMore:NO];
    }
    else {
        [self setEnableLoadMore:YES];
    }
    [self resetPullTableViewState];
    [self.tableView reloadData];
}

#pragma mark - Private
- (void)setupHeaderView
{
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 40)];
    view.backgroundColor = [UIColor colorWithWhite:0.92 alpha:1];
    [self.view addSubview:view];
    view.layer.borderWidth = 0.5;
    view.layer.borderColor = [UIColor grayColor].CGColor;
    self.headerView = view;
    
    UIButton* btnArea = [self createHeaderButton:@"区域" selector:@selector(onClickArea:)];
    CGRect frame = btnArea.frame;
    frame.size.width = self.view.bounds.size.width;
//    btnArea.center = CGPointMake(view.bounds.size.width/2, view.bounds.size.height/2);
    [view addSubview:btnArea];
    
//    UIButton* btnNearby = [self createHeaderButton:@"附近" selector:@selector(onClickNearby:)];
//    btnNearby.center = CGPointMake(view.bounds.size.width*3/4, view.bounds.size.height/2);
//    [view addSubview:btnNearby];
    
//    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(view.bounds.size.width/2-0.5, 11, 1, view.bounds.size.height - 20)];
//    line.backgroundColor = [UIColor darkGrayColor];
//    [view addSubview:line];
    
    [self setupHeaderPopupView];
}

- (void)setupHeaderPopupView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, self.headerView.bounds.size.height, self.view.bounds.size.width, self.view.bounds.size.height - self.headerView.bounds.size.height)];
    view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    [self.view insertSubview:view belowSubview:self.headerView];
    view.hidden = YES;
    self.headerPopupView = view;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapHeaderPopupView:)];
    tapGesture.cancelsTouchesInView = NO;
    [view addGestureRecognizer:tapGesture];
    
    UIView *btnView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, HEADER_BUTTON_HEIGHT*self.areaList.count+0.5*(self.areaList.count-1))];
    btnView.backgroundColor = self.headerView.backgroundColor;
    btnView.tag = 1000;
    btnView.layer.borderWidth = 0.5;
    btnView.layer.borderColor = [UIColor darkGrayColor].CGColor;
    [view addSubview:btnView];
    
    CGFloat y = 0;
    for (int i=0; i<self.areaList.count; i++) {
        UIButton *btn = [self createHeaderButton:self.areaList[i] selector:@selector(onClickAreaCategory:)];
        CGRect frame = btn.frame;
        frame.origin.y = y;
        btn.frame = frame;
        [btnView addSubview:btn];
        
        y += HEADER_BUTTON_HEIGHT;
        if (i < self.areaList.count-1) {
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(8, y, btnView.bounds.size.width - 16, 0.5)];
            line.backgroundColor = [UIColor grayColor];
            [btnView addSubview:line];
            y += 0.5;
        }
    }
}

- (UIButton*)createHeaderButton:(NSString*)title selector:(SEL)selector
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, self.headerView.bounds.size.width, HEADER_BUTTON_HEIGHT);
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn addTarget:self action:selector forControlEvents:UIControlEventTouchDown];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    return btn;
}

- (void)showHeaderPopupView
{
    self.headerPopupView.hidden = NO;
    UIView *btnView = [self.headerPopupView viewWithTag:1000];
    btnView.center = CGPointMake(btnView.bounds.size.width/2, -btnView.bounds.size.height/2);
    [UIView animateWithDuration:0.3 animations:^{
        btnView.center = CGPointMake(btnView.bounds.size.width/2, btnView.bounds.size.height/2);
    } completion:^(BOOL finished){
        
    }];
}

- (void)hideHeaderPopupView
{
    UIView *btnView = [self.headerPopupView viewWithTag:1000];
    [UIView animateWithDuration:0.3 animations:^{
        btnView.center = CGPointMake(btnView.bounds.size.width/2, -btnView.bounds.size.height/2);
    } completion:^(BOOL finished){
        self.headerPopupView.hidden = YES;
    }];
}

- (void)loadCellData:(UITableViewCell*)cell index:(int)index
{
    if (index >= self.storeList.count) {
        return;
    }
    
    NSDictionary* cellData = self.storeList[index];
    NSString *path = [Common valueForKey:P_LOGO_PATH dic:cellData];
    NSString *name = [Common valueForKey:P_NAME dic:cellData];
    UIImageView *imageView = (UIImageView*)[cell viewWithTag:1000];
    [imageView setImageWithURL:[Common getFullDownloadPathByRelativePath:path] placeholderImage:[Common getPlaceholderImage:ePIT_StoreLogo]];
    
    UILabel *lbName = (UILabel*)[cell viewWithTag:1100];
    lbName.text = name;
    
    UIView *contentView = [self createContentView:index];
    if (contentView != nil) {
        contentView.tag = 10000;
        UIView *view = [cell.contentView viewWithTag:2000];
        UIView *oldView = [view viewWithTag:10000];
        [oldView removeFromSuperview];
        [view addSubview:contentView];
    }
    else {
        CGFloat star = [[Common valueForKey:P_STAR dic:cellData] floatValue];
        NSString *address = [Common valueForKey:P_ADRESS dic:cellData];
        UILabel *lbAddress = (UILabel*)[cell viewWithTag:1302];
        lbAddress.text = [NSString stringWithFormat:@"地址:%@", address];
        
        [self setupStarViewForCell:cell star:star];
    }
}

- (void)setupStarViewForCell:(UITableViewCell*)cell star:(CGFloat)star
{
    UIView *starView = [cell viewWithTag:1200];
    for (UIView* view in starView.subviews) {
        [view removeFromSuperview];
    }
    
    HotRateView *hotView = [[HotRateView alloc] initWithHotRate:star];
    CGRect frame = hotView.frame;
    frame.origin.x = 0;
    frame.origin.y = (starView.bounds.size.height - hotView.bounds.size.height)/2;
    hotView.frame = frame;
    [starView addSubview:hotView];
}

- (UIView*)createContentView:(int)index
{
    NSDictionary* cellData = self.storeList[index];
    CGFloat star = [[Common valueForKey:P_STAR dic:cellData] floatValue];
    NSString *address = [Common valueForKey:P_ADRESS dic:cellData];
    int price = [[Common valueForKey:P_BASE_PRICE dic:cellData] intValue];
    NSString *phone = [Common valueForKey:P_PHONE dic:cellData];
    
    UIView *view = [[NSBundle mainBundle] loadNibNamed:@"StoreListCell"  owner:self options:nil][1];
    UILabel *lb1 = (UILabel*)[view viewWithTag:10001];
    UILabel *lb2 = (UILabel*)[view viewWithTag:10002];
    UILabel *lb3 = (UILabel*)[view viewWithTag:10003];
    switch (self.type) {
        case 4:
        {
            lb1.text = [NSString stringWithFormat:@"电话:%@", phone];
            lb2.text = [NSString stringWithFormat:@"地址:%@", address];
            lb2.numberOfLines = 2;
            break;
        }
        case 5:
        {
            lb1.text = @"星级：";
            HotRateView *hotView = [[HotRateView alloc] initWithHotRate:star];
            CGRect frame = hotView.frame;
            frame.origin.x = 42;
            frame.origin.y = (view.bounds.size.height/3 - hotView.bounds.size.height)/2 - 2;
            hotView.frame = frame;
            [view addSubview:hotView];
            lb2.text = [NSString stringWithFormat:@"价格:%d元起", price];
            lb3.text = [NSString stringWithFormat:@"地址:%@", address];
            break;
        }
        case 6:
        {
            NSString *ticket = @"门票：无";
            if (price > 0) {
                ticket = [NSString stringWithFormat:@"门票:%d元", price];
            }
            lb1.text = ticket;
            lb2.text = [NSString stringWithFormat:@"地址:%@", address];
            lb2.numberOfLines = 2;
            break;
        }
        case 7:
        {
            lb1.text = [NSString stringWithFormat:@"地址:%@", address];
            lb1.numberOfLines = 3;
            break;
        }
        default:
            return nil;
    }
    [lb1 sizeToFit];
    [lb2 sizeToFit];
    [lb3 sizeToFit];
    CGRect frame = lb1.frame;
    frame.size.width = MIN(frame.size.width, view.bounds.size.width);
    lb1.frame = frame;
    frame = lb2.frame;
    frame.size.width = MIN(frame.size.width, view.bounds.size.width);
    lb2.frame = frame;
    frame = lb3.frame;
    frame.size.width = MIN(frame.size.width, view.bounds.size.width);
    lb3.frame = frame;
    return view;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.storeList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return STORE_LIST_CELL_HEIGHT;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StoreListCell"];
    // Configure the cell...
    if(cell == nil)
    {
        cell = [[NSBundle mainBundle] loadNibNamed:@"StoreListCell"  owner:self options:nil][0];
        UIImageView* imgView = (UIImageView*)[cell viewWithTag:1301];
        imgView.image = [UIImage imageNamed:@"hotel/map.png"];
    }
    [self loadCellData:cell index:indexPath.row];
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row >= self.storeList.count) {
        return;
    }
    NSDictionary* dic = self.storeList[indexPath.row];
    StoreDetailViewController *storeDetailViewCtrl = [[StoreDetailViewController alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    storeDetailViewCtrl.storeId = [[Common valueForKey:P_ID dic:dic] intValue];
    [self.navigationController pushViewController:storeDetailViewCtrl animated:YES];
}

#pragma mark - PullTableViewDelegate
- (void)pullTableViewDidTriggerRefresh:(PullTableView*)pullTableView
{
    NSLog(@"refresh...");
    self.currentIndex = -1;
    [self getStoreList];
}

-(void)pullTableViewDidTriggerLoadMore:(PullTableView *)pullTableView
{
    NSLog(@"loadMore...");
    [self getStoreList];
}

- (void)resetPullTableViewState
{
    [self setPullTableIsRefreshing:NO];
    [self setPullTableIsLoadMore:NO];
}

@end
